/**
 * all EventApi Control
 * @namespace EventApi
 * @example 使用示例
    import EventApi from "@module/EventApi";
    //----class 使用实例：
    //在constructor中定义以下：
    let _self = this;
    function updateEvent(value) {
        _self.toggleShiftAccount(value);
    }
    this.cleanEvent = EventApi.on("showShiftAccount", updateEvent);
    //在组件卸载时取消监听
    componentWillUnmount() {
        this.cleanEvent();
    }
    //任意位置触发事件：
    EventApi.emit("showShiftAccount", false);
    //----hook 使用实例：
 */

let EventApi = {
    EventInfo: {},
    setEventValue: function(eventName, value, dispatch) {
        return (EventApi.EventInfo[eventName].eventValue = dispatch(value));
    },
    initCurrentEventValue: function(eventName) {
        if (!EventApi.EventInfo[eventName]) {
            EventApi.EventInfo[eventName] = {};
            EventApi.EventInfo[eventName].hookList = [];
        }
    },
    getEventValue: function(eventName) {
        EventApi.initCurrentEventValue(eventName);
        return EventApi.EventInfo[eventName].eventValue;
    },
    on: function(eventName, cb) {
        if (typeof cb === "function") {
            EventApi.initCurrentEventValue(eventName);
            if (EventApi.EventInfo[eventName].hookList.indexOf(cb) === -1) {
                EventApi.EventInfo[eventName].hookList.push(cb);
                return () => {
                    EventApi.off(eventName, cb);
                };
            }
        }
    },
    emit: function(eventName, value, dispatch) {
        EventApi.initCurrentEventValue(eventName);
        dispatch =
            dispatch ||
            function(value) {
                return value;
            };
        value = EventApi.setEventValue(eventName, value, dispatch);
        for (
            let i = EventApi.EventInfo[eventName].hookList.length - 1;
            i >= 0;
            i--
        ) {
            let item = EventApi.EventInfo[eventName].hookList[i];
            item(value);
        }
    },
    off: function(eventName, cb) {
        EventApi.initCurrentEventValue(eventName);
        let ps = EventApi.EventInfo[eventName].hookList.indexOf(cb);
        if (ps > -1) {
            EventApi.EventInfo[eventName].hookList.splice(ps, 1);
            EventApi._checkEventHookList(eventName);
        }
    },
    _checkEventHookList: function(eventName) {
        if (EventApi.EventInfo[eventName].hookList.length === 0) {
            EventApi.cleanEvent(eventName);
        }
    },
    cleanEvent: function(eventName) {
        delete EventApi.EventInfo[eventName];
    },
    getEventInfo: function() {
        return EventApi.EventInfo;
    },
    setEvent: function(eventName, value, dispatch) {
        EventApi.emit(eventName, value, dispatch);
    },
    validateEvent: function() {}
};

global.EventApi = EventApi;

export default EventApi;
